<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="form" ref="formRef" :rules="rules" label-width="110px">
      <div class="flex justify-between">
        <div class="w-100%">
          <el-form-item :label="t('logisticsClassification.cc_name')" prop="cc_name">
            <el-input
              v-model="form.cc_name"
              clearable
              :placeholder="t('logisticsClassification.cc_name')"
            />
          </el-form-item>

          <el-form-item :label="t('logisticsClassification.sellable_wids')" prop="sellable_wids">
            <el-tree-select
              ref="treeRef"
              v-model="form.sellable_wids"
              :data="modelList"
              :props="{ label: 'label', value: 'value' }"
              multiple
              show-checkbox
              check-strictly
              node-key="value"
              draggable
              :allow-drag="allowDrag"
              :allow-drop="allowDrop"
              @node-drop="handleDrop"
              @check="handleCheck"
              style="width: 100%"
            >
              <template #default="{ data }">
                <span>{{ data.label }}</span>
              </template>
            </el-tree-select>
          </el-form-item>

          <el-form-item :label="t('logisticsClassification.assignment')" prop="assignment">
            <el-select
              v-model="form.assignment"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
              placeholder="请选择国家"
              style="width: 100%"
              @click="openCountryDialog"
            >
              <el-option
                v-for="item in selectedCountries"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </ContentDetailWrap>

  <UploadDialog ref="DialogUploadRef" @expose-upload-data="exposeUploadData" />
  <CountryDialog ref="countryDialogRef" @confirm="handleCountryConfirm" />
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { createDataApi } from '@/api/logisticsClassification'
import UploadDialog from '@/views/Market/VideoManage/components/DialogUpload/index.vue'
import { Sort } from '@element-plus/icons-vue'
import { getfirstWarehouseListApi } from '@/api/warehouse'
import CountryDialog from './components/countryDialog/index.vue'
import { ref, reactive, nextTick } from 'vue'
import type { CountryItem } from './components/countryDialog/types'

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()

interface ModelItem {
  label: string
  value: string | number
}

interface FormData {
  cc_name: string
  sellable_wids: (string | number)[]
  assignment: string[]
  countries: string[]
}

const loading = ref<boolean>(false)
const modelList = ref<ModelItem[]>([])
const DialogUploadRef = ref<InstanceType<typeof UploadDialog>>()
const treeRef = ref()

const form = reactive<FormData>({
  cc_name: '',
  sellable_wids: [],
  assignment: [] as string[],
  countries: [] as string[]
})

const rules = ref<FormRules>({
  cc_name: [
    {
      required: true,
      message: t('logisticsClassification.ccNameMsg'),
      trigger: 'change'
    }
  ]
})

const beforeUpload = (file) => {
  // 阻止文件选择窗口弹出的逻辑
  return false // 返回 false 阻止默认的文件选择窗口
}

interface FileItem {
  uid: string
  name: string
  url: string
  type: string
  id: string
}

const fileList = ref<any[]>([])
const formRef = ref<FormInstance>()

const uploadPayment = () => {
  nextTick(() => {
    DialogUploadRef.value!.dialogVisible = true
    DialogUploadRef.value?.getBackShow(fileList.value)
  })
}

const exposeUploadData = (list: FileItem[]) => {
  fileList.value = list
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const submitData = {
        cc_name: form.cc_name,
        sellable_wids: form.sellable_wids.join(','),
        country_ids: form.countries.join(',')
      }
      const resp = await createDataApi(submitData)
      if (resp.code === 0) {
        ElMessage.success(t('system.parameterConfig.createSucMsg'))
        push({ path: '/logistics/classification' })
      }
    }
  })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getfirstWarehouseListApi({ status: 1 })
  modelList.value = resp.data.list
}

const previewFile = (file: FileItem) => {
  // Preview logic here
  window.open(file.url, '_blank')
}

const removeFile = (file: FileItem) => {
  // Remove logic (e.g., update fileList or call API)
  fileList.value = fileList.value.filter((f) => f.uid !== file.uid)
  ElMessage.success('File removed')
}

const allowDrag = (node: any) => {
  return true
}

const allowDrop = (draggingNode: any, dropNode: any, type: string) => {
  // 只允许在同一层级内拖动排序
  if (draggingNode.level !== dropNode.level) {
    return false
  }
  // 只允许在before和after位置放置
  return type !== 'inner'
}

const handleDrop = (draggingNode: any, dropNode: any, dropType: string) => {
  // 获取当前层级的所有节点
  const nodes = modelList.value
  const draggingIndex = nodes.findIndex((node) => node.value === draggingNode.data.value)
  let dropIndex = nodes.findIndex((node) => node.value === dropNode.data.value)

  // 移除拖动的节点
  const [draggedNode] = nodes.splice(draggingIndex, 1)

  // 调整放置位置
  if (draggingIndex < dropIndex) {
    dropIndex--
  }

  // 根据放置类型插入到新位置
  if (dropType === 'before') {
    nodes.splice(dropIndex, 0, draggedNode)
  } else if (dropType === 'after') {
    nodes.splice(dropIndex + 1, 0, draggedNode)
  }

  // 更新数据
  modelList.value = [...nodes]

  // 保持选中状态并更新顺序
  nextTick(() => {
    const checkedNodes = treeRef.value.getCheckedNodes()
    form.sellable_wids = checkedNodes.map((node) => node.value)
    treeRef.value.setCheckedKeys(form.sellable_wids)
  })
}

const handleCheck = (data: ModelItem, checked: boolean) => {
  const checkedNodes = treeRef.value.getCheckedNodes()
  form.sellable_wids = checkedNodes.map((node) => node.value)
}

const countryDialogRef = ref()
const selectedCountries = ref<CountryItem[]>([])

const openCountryDialog = () => {
  countryDialogRef.value?.open(selectedCountries.value, true)
}

const handleCountryConfirm = (countries: CountryItem[]) => {
  selectedCountries.value = countries
  form.assignment = countries.map((country) => country.name)
  form.countries = countries.map((country) => country.id)
}

onMounted(() => {
  getDropDownBoxInfo()
})
</script>
<style lang="less" scoped>
.file-list-container {
  margin-top: 20px;
}

.el-upload-list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.el-upload-list__item {
  display: flex;
  padding: 4px 8px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  align-items: center;
  justify-content: space-between;
}

.el-upload-list__item-name {
  flex-grow: 1;
  color: #606266;
  text-decoration: none;
}

.el-upload-list__item-name:hover {
  color: #409eff;
}

.el-icon-view,
.el-icon-delete {
  margin-left: 10px;
  color: #606266;
  cursor: pointer;
}

.el-icon-view:hover {
  color: #409eff;
}

.el-icon-delete:hover {
  color: #f56c6c;
}
</style>
